<?php
/**
 * DefaultController class.
 * DefaultController is default action for API REST.
 * 
 * LBB Solutions Ltd. 版权所有 @ 2012.
 */
class DefaultController extends ApiController
{
	public function actionIndex()
	{
		$this->_sendJSON(500, 'no API!');
	}
	
	public function actionGetAddress()
	{
		$lat = Yii::app()->request->getParam('lat', null);
		$lng = Yii::app()->request->getParam('lng', null);
		if (empty($lat)) $this->_sendError('The parameter "lat" is missing!');
		if (empty($lng)) $this->_sendError('The parameter "lng" is missing!');
		
		//Use google API to get address
		$address = self::GoogleAddress($lat, $lng);
		
		self::APILogging('geo', array($lat, $lng, $address), 'geo');
		$this->_sendJSON(200, $address);
	}
	
	protected static function GoogleAddress($lat, $lng) {
		// http://maps.googleapis.com/maps/api/geocode/json?latlng=61,24&sensor=false
		$latLng = $lat . ',' . $lng;
		$url = "http://maps.google.com/maps/api/geocode/json?latlng={$latLng}&sensor=false";
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		$response = curl_exec($ch);
		curl_close($ch);
		$json = json_decode($response);
		return $json->results[0]->formatted_address;
	}
	
	protected static function GoogleGeo($address) {
		// http://maps.googleapis.com/maps/api/geocode/json?address=armas+launiksenkatu&sensor=false
		$url = "http://maps.google.com/maps/api/geocode/json?address={$address}&sensor=false";
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		$response = curl_exec($ch);
		curl_close($ch);
		$json = json_decode($response);
		return array(
			'lat' => $json->results[0]->geometry->location->lat,
			'lng' => $json->results[0]->geometry->location->lng,
		);
	}
}